import pygame, tile, scenes

from pygame.locals import *
from tile import *
from constants import *

class MobManager:
    """Manages a list of mobs for a map."""
    def __init__(self, mobs, player, tileMap):
        """Initializes a MobManager with the specified parameters"""
        self.mobs = mobs
        self.tileMap = tileMap
        self.player = player
        self.activeEncounter = None
        
    def addMob(self, mob):
        """Adds a mob to the MobManager"""
        self.mobs.append(mob)

    def removeMob(self, mob):
        """Removes a mob from the MobManager"""
        self.mobs.remove(mob)

    def updateMobs(self):
        """Updates each mob, running the code in their update() method and moving them if they want to make a valid move"""
        for mob in self.tileMap.mobs:
            mob.update()
            self.checkMove(mob)
                
        self.checkMove(self.player)

    def checkMove(self, mob):
        """Determines whether a mob can move as it has requested. If not, resets the mob's movegoal. If it can, it moves the mob before resetting the mob's movegoal"""
        if mob.moveGoal == [0, 0]:
            return

        oldX = mob.rect.topleft[0] / TILESIZE
        oldY = mob.rect.topleft[1] / TILESIZE

        #Calculate the x/y coordinates in the map that the mob is trying to move to (in tiles)
        xGoal = ((mob.rect.topleft[0] + (mob.moveGoal[0] * TILESIZE)) / TILESIZE)
        yGoal = ((mob.rect.topleft[1] + (mob.moveGoal[1] * TILESIZE)) / TILESIZE)

        canMove = True
        for layer in self.tileMap.layers:
            try:
                if layer[xGoal][yGoal].solid:
                    canMove = False
                    break
            except Exception:
                #filthy coding to handle cases where layers aren't the same size
                canMove = True
                break

        #now check if we're going to run into any mobs
        if self.tileMap.isInside:
            for otherMob in self.tileMap.mobs:
                if mob == otherMob:
                    continue
                #check to see if they're on the tile we're trying to move to


                if xGoal == otherMob.getTileCoords()[0] and yGoal == otherMob.getTileCoords()[1]:
                    self.activeEncounter = scenes.Encounter(otherMob, mob, self.tileMap.scene)
                    canMove = False
                    break

        if canMove:
            #actually move the mob! calculate the new rect position by converting xGoal and yGoal to actual pixels
            mob.rect.topleft = (xGoal * TILESIZE, yGoal * TILESIZE)
